<?php

/**
 * @author      Nguyen Duc Thuan <me@ndthuan.com>
 * @copyright   Copyright (c) 2009 Nguyen Duc Thuan <me@ndthuan.com>
 */
class Fete_View_Helper_HeadLink extends Fete_View_Helper
{
    protected $_links   = '';
    protected $_linkTag = 'LINK';
    protected $_closeStyle = '';

    public function &headLink($href = null, $type = null, $extras = array())
    {
        if (null !== $href) {
            $this->appendLink($href, $type, $extras);
        }
        return $this;
    }

    public function &prependLink($href, $type = null, $extras = array())
    {
        $this->_links = $this->_genHtml($href, $type, $extras) . $this->_links;

        return $this;
    }

    public function &appendLink($href, $type = null, $extras = array())
    {
        $this->_links .= $this->_genHtml($href, $type, $extras);

        return $this;
    }

    protected function _genHtml($href, $type = null, $extras = array())
    {
        ob_start();
        echo '<', $this->_linkTag, ' href="', $href, '"';

        if (null !== $type) {
            echo ' type="', $type, '"';
        }

        foreach ($extras as $attrib => $value)
        {
            if (null !== $value) {
                echo ' ', $attrib, '="', $value, '"';
            }
        }

        echo $this->_closeStyle, '>';

        return ob_get_clean();
    }

    public function __construct()
    {
        if ('XHTML' === substr($this->docType()->getDocType(), 0, 5)) {
            $this->_linkTag = 'link';
            $this->_closeStyle = ' /';
        }
    }

    public function __toString()
    {
        return $this->_links;
    }
}